<script setup>
import {nextTick, onMounted, onUnmounted, ref} from "vue"
import {ChromeFilled, Delete, DocumentCopy, InfoFilled, Picture, Plus, UploadFilled} from "@element-plus/icons-vue";
import nodata from "@/assets/img/no-data.png";
import Compressor from "compressorjs";
import {httpGet, httpPost} from "@/utils/http";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import Clipboard from "clipboard";
import {checkSession, getClientId, getSystemInfo} from "@/store/cache";
import {useRouter} from "vue-router";
import {getSessionId} from "@/store/session";
import {copyObj, removeArrayItem} from "@/utils/libs";
import {useSharedStore} from "@/store/sharedata";
import TaskList from "@/components/TaskList.vue";
// 回到顶部组件
import BackTop from "@/components/BackTop.vue";
import {showMessageError} from "@/utils/dialog";
// 右侧任务DOM容器高度
const listBoxHeight = ref(0)
// 左侧绘图参数DOM高度
const paramBoxHeight = ref(0)
const loading = ref(true)
// 瀑布流卡片宽度，现在不同屏宽使用不同宽度需要自己写函数返回对应宽度
const colWidth = ref(250)
// 预览图片地址
const previewURL = ref('')
const store = useSharedStore()

// 根据窗口大小动态调整两个元素的高度
const resizeElement = () => {
  listBoxHeight.value = window.innerHeight - 80
  paramBoxHeight.value = window.innerHeight - 160
}
resizeElement()
// 当浏览器窗口大小改变时触发
window.onresize = () => {
  resizeElement()
}

// 图片比例
const rates = [
  {css: "square", value: "1:1", text: "1:1", img: "/images/mj/rate_1_1.png"},
  {css: "size1-2", value: "1:2", text: "1:2", img: "/images/mj/rate_1_2.png"},
  {css: "size2-1", value: "2:1", text: "2:1", img: "/images/mj/rate_2_1.png"},
  {css: "size2-3", value: "2:3", text: "2:3", img: "/images/mj/rate_3_4.png"},
  {css: "size3-2", value: "3:2", text: "3:2", img: "/images/mj/rate_4_3.png"},
  {css: "size3-4", value: "3:4", text: "3:4", img: "/images/mj/rate_3_4.png"},
  {css: "size4-3", value: "4:3", text: "4:3", img: "/images/mj/rate_4_3.png"},
  {css: "size16-9", value: "16:9", text: "16:9", img: "/images/mj/rate_16_9.png"},
  {css: "size9-16", value: "9:16", text: "9:16", img: "/images/mj/rate_9_16.png"},
]

// 模型
const models = [
  {text: "写实模式MJ-6.1", value: " --v 6.1", img: "/images/mj/mj-v6.png"},
  {text: "优质模式MJ-6.0", value: " --v 6", img: "/images/mj/mj-v5.2.png"},
  {text: "优质模式MJ-5.2", value: " --v 5.2", img: "/images/mj/mj-v5.1.jpg"},
  {text: "虚幻模式MJ-5.1", value: " --v 5.1", img: "/images/mj/mj-v5.jpg"},
  {text: "真实模式MJ-4", value: " --v 4", img: "/images/mj/mj-v4.jpg"},
  {text: "动漫风-niji4", value: " --niji 4", img: "/images/mj/nj4.jpg"},
  {text: "动漫风-niji5", value: " --niji 5", img: "/images/mj/mj-niji.png"},
  {text: "动漫风-niji5 可爱", value: " --niji 5 --style cute", img: "/images/mj/nj1.jpg"},
  {text: "动漫风-niji5 风景", value: " --niji 5 --style scenic", img: "/images/mj/nj2.jpg"},
  {text: "动漫风-niji6", value: " --niji 6", img: "/images/mj/nj3.jpg"},
]

// 图片画质
const options = [
  {
    value: 0,
    label: '默认'
  },
  {
    value: 0.25,
    label: '普通'
  },
  {
    value: 0.5,
    label: '清晰'
  },
  {
    value: 1,
    label: '高清'
  },
]

const router = useRouter()
const initParams = {
  client_id: getClientId(), // 客户端Id
  task_type: 'image', // 任务类型
  rate: rates[0].value, // 图片比例
  model: models[0].value, // 模型风格
  chaos: 0, // 创意度
  stylize: 0, // 风格化
  seed: 0, // 随机种子
  img_arr: [],
  raw: false, // 是否为原始模式
  iw: 0, // 图生图参考权重
  prompt: router.currentRoute.value.params['prompt'] ?? "", // 提示词：从路由中获取名为 prompt 的 路由参数 (route param)，如果参数不存在则返回空字符串
  neg_prompt: '',
  tile: false, // 重复平铺
  quality: 0, // 图片画质
  cref: '', // 角色一致性图片
  sref: '', // 风格一致性图片
  cw: 0 // 图片一致性参考权重
}

const params = ref(copyObj(initParams))
// 图片列表
const imgList = ref([])
// 选择的操作
const activeName = ref('txt2img')
// 正在运行的任务列表
const runningJobs = ref([])
// 已经完成的任务列表
const finishedJobs = ref([])
// 用户当前算力
const power = ref(0)
// 用户Id
const userId = ref(0)
// 是否登录
const isLogin = ref(false)

const clipboard = ref(null)

// MJ绘图消耗算力
const mjPower = ref(1)
// MJ操作消耗算力
const mjActionPower = ref(1)
const page = ref(0)
const pageSize = ref(15)
// 记录获取任务列表的数据是不是到最后了
const isOver = ref(false)

onMounted(() => {
  initData()
  // .copy-prompt-mj 绑定在生成号的任务上复制提示词使用
  clipboard.value = new Clipboard('.copy-prompt-mj')
  clipboard.value.on('success', () => {
    ElMessage.success('复制成功！')
  })
  clipboard.value.on('error', () => {
    ElMessage.success('复制失败！')
  })
  // 当服务端回复消息的时候会触发 callback 回调函数，data 就是服务端返回的消息
  store.addMessageHandler('mj', (data) => {
    console.log("MJ：",data)
    // 丢弃无关的消息
    if (data.channel !== 'mj' || data.clientId !== getClientId()) {
      return
    }
    if (data.body === 'FINISH' || data.body === 'FAIL') {
      page.value = 0
      isOver.value = false
      fetchFinishJobs()
    }
    nextTick(() => {
      fetchRunningJobs()
    })
  })
})

onUnmounted(() => {
  clipboard.value.destroy()
  // 移除websocket监听事件
  store.removeMessageHandler('mj')
})

// 初始化数据
const initData = () => {
  // 从系统配置中获取 mj 操作消耗的算力
  getSystemInfo().then(res => {
    mjPower.value = res.data['mj_power']
    mjActionPower.value = res.data['mj_action_power']
  }).catch(e => {
    showMessageError('获取系统配置失败：' + e.message)
  })
  checkSession().then(user => {
    power.value = user['power']
    userId.value = user.id
    isLogin.value = true
    page.value = 0
    fetchRunningJobs()
    fetchFinishJobs()
  }).catch(() => {
  })
}

// 获取运行中的任务
const fetchRunningJobs = () => {
  if (!isLogin.value) {
    return
  }

  httpGet(`api/mj/jobs?finish=false`).then(res => {
    const jobs = res.data.items
    const _jobs = []
    for (let i = 0; i < jobs.length; i++) {
      // 101 表示任务执行失败
      if (jobs[i].progress === 101) {
        ElNotification({
          title: '任务执行失败',
          dangerouslyUseHTMLString: true,
          message: `任务ID：${jobs[i]['task_id']}<br/>原因：${jobs[i]['err_msg']}`,
          type: 'error',
          duration: 0,
        })
        if (jobs[i].type === 'image') {
          power.value += mjPower.value
        } else {
          power.value += mjActionPower.value
        }
      }
      _jobs.push(jobs[i])
    }
    runningJobs.value = _jobs
  }).catch(e => {
    showMessageError('获取任务失败：' + e.message)
  })
}

// 查询已经完成的任务
const fetchFinishJobs = () => {
  // 判断是否登录 并且 数据是不是获取到最后了
  if (!isLogin.value || isOver.value) {
    return
  }

  loading.value = true
  page.value = page.value + 1
  // 获取已经完成的任务
  httpGet(`api/mj/jobs?finish=true&page=${page.value}&page_size=${pageSize.value}`).then(res => {
    const jobs = res.data.items
    for (let i = 0; i < jobs.length; i++) {
      if (jobs[i]['img_url'] !== '') {
        if (jobs[i].type === 'upscale' || jobs[i].type === 'swapFace') {
          jobs[i]['thumb_url'] = jobs[i]['img_url'] + '?imageView2/1/w/480/h/600/q/75'
        } else {
          jobs[i]['thumb_url'] = jobs[i]['img_url'] + '?imageView2/1/w/480/h/480/q/75'
        }
      } else {
        jobs[i]['thumb_url'] = '/image/img-placeholder.jpg'
      }

      if (jobs[i].type !== 'upscale' && jobs[i].progress === 100) {
        jobs[i]['can_opt'] = true
      }
    }
    // 判断获取到的数据是否小于 我们每页的数据，如果小于就表示已经是最后的数据了
    if (jobs.length < pageSize.value) {
      isOver.value = true
    }
    // 如果是第一页，直接把数据赋值给 finishedJobs，如果不是就把获取到的数据累加到 finishedJobs 中
    if (page.value === 1) {
      finishedJobs.value = jobs
    } else {
      finishedJobs.value = finishedJobs.value.concat(jobs)
    }
    loading.value = false
  }).catch(e => {
    showMessageError('获取任务失败：' + e.message)
  })
}

// 切换图片比例
const changeRate = (item) => {
  params.value.rate = item.value
}

// 切换模型
const changeModel = (item) => {
  params.value.model = item.value
}

const imgKey = ref('')
// 上传图片前先把图片的key进行设置
const beforeUpload = (key) => {
  imgKey.value = key
}

// 图片上传
const uploadImg = (file) => {
  if (!isLogin.value) {
    store.setShowLoginDialog(true)
    return
  }

  // 压缩图片并上传
  new Compressor(file.file, {
    quality: 0.6,
    success(result) {
      const formData = new FormData()
      formData.append('file', result, result.name)
      // 执行上传操作
      httpPost('api/file/upload', formData).then(res => {
        if (imgKey.value === '') {
          imgList.value.push(res.data.url)
        } else {
          params.value[imgKey.value] = res.data.url
          imgKey.value = ''
        }
        ElMessage.success('上传成功')
      }).catch(e => {
        showMessageError('上传失败：' + e.message)
      })
    },
    error(error) {
      showMessageError('图片压缩失败：' + err.message)
    }
  })
}

const promptRef = ref(null)
// 创建绘图任务
const generate = () => {
  if (!isLogin.value) {
    store.setShowLoginDialog(true)
    return
  }

  // 判断提示词
  if (params.value.prompt === '' && params.value.task_type === 'image') {
    // 提示词输入框聚集焦点
    promptRef.value.focus()
    return ElMessage.error('请输入绘图提示词！')
  }

  // 判断是不是动漫模型
  if (params.value.model.indexOf('niji') !== -1 && params.value.raw) {
    return ElMessage.error("动漫模型不允许启用原始模式")
  }

  // 如果要执行的事换脸任务，图片必须是两张
  if (imgList.value.length !== 2 && params.value.task_type === 'swapFace') {
    return ElMessage.error("换脸操作需要上传两张图片")
  }
  httpPost('api/mj/image', params.value).then(() => {
    ElMessage.success('绘图任务推送成功，请耐心等待任务执行...')
    power.value -= mjPower.value
    // 查询正在执行的任务
  }).catch(e => {
    showMessageError('任务推送失败：' + e.message)
  })
}

// 图片放大任务
const upscale = (index, item) => {
  sendTaskInstruction('api/mj/upscale', index, item)
}

// 图片变换任务
const variation = (index, item) => {
  sendTaskInstruction('api/mj/variation', index, item)
}

// 发送任务指令请求
const sendTaskInstruction = (url, index, item) => {
  httpPost(url, {
    index: index,
    client_id: getClientId(),
    channel_id: item.channel_id,
    message_id: item.message_id,
    message_hash: item.hash,
    session_id: getSessionId(),
    prompt: item.prompt,
  }).then(() => {
    ElMessage.success('任务推送成功，请耐心等待任务执行...')
    power.value = mjActionPower.value
    // 查询正在执行的任务
    fetchRunningJobs()
  }).catch(e => {
    showMessageError('任务推送失败：' + e.message)
  })
}

// 删除任务和图片
const removeImage = (item) => {
  ElMessageBox.confirm(
      '此操作将会删除任务和图片，继续操作吗?',
      '删除提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    httpGet('api/mj/remove', {id: item.id, user_id: item.user_id}).then(() => {
      ElMessage.success('任务删除成功')
      page.value = 0
      isOver.value = false
      // 重新加载已经完成的任务列表
      fetchFinishJobs()
    }).catch(e => {
      showMessageError('任务删除失败：' + e.message)
    })
  }).catch(() => {
  })
}

// 发布图片到照片墙
const publishImage = (item, action) => {
  let text = '图片发布'
  if (action === false) {
    text = '取消发布'
  }
  httpGet('api/mj/publish', {id: item.id, action: action, user_id: item.user_id}).then(() => {
    item.publish = action
    page.value = 0
    isOver.value = false
    item.publish = action
  }).catch(e => {
    ElMessage.error(text + '失败：' + e.message)
  })
}

// 点击已经完成的任务图片，会把图片地址传递给预览图片地址，页面显示预览图片
const previewImg = (item) => {
  previewURL.value = item.img_url
}

// 切换菜单
const tabChange = (tab) => {
  if (tab === 'txt2img' || tab === 'img2img' || tab === 'cref') {
    params.value.task_type = 'image'
  } else {
    params.value.task_type = tab
  }
}

// 删除已经上传的图片
const removeUploadImage = (url) => {
  imgList.value = removeArrayItem(imgList.value, url)
}

// 是否生成专业绘图指令
const isGenerating = ref(false)
// 生成专业绘图指令
const generatePrompt = () => {
  if (params.value.prompt === '') {
    return showMessageError('请输入原始提示词')
  }
  isGenerating.value = true
  httpPost('api/prompt/image', {prompt: params.value.prompt}).then(res => {
    params.value.prompt = res.data
    isGenerating.value = false
  }).catch(e => {
    isGenerating.value = false
    showMessageError('生成专业提示词失败：' + e.message)
  })
}

</script>

<template>
  <div class="page-mj">
    <div class="inner custom-scroll">
      <!-- 侧边绘图参数 -->
      <div class="mj-box">
        <h2>MidJourney 创作中心</h2>
        <div class="mj-params" :style="{height: paramBoxHeight + 'px'}">
          <el-form :model="params" label-width="80px" label-position="left">
            <!--  图片比例标题提示 -->
            <div class="param-line pt">
              <span>图片比例：</span>
              <el-tooltip content="生成图片的尺寸比例" placement="right">
                <el-icon>
                  <InfoFilled/>
                </el-icon>
              </el-tooltip>
            </div>
            <!--  图片比例参数渲染 -->
            <div class="param-line pt">
              <el-row :gutter="10">
                <el-col :span="8" v-for="item in rates" :key="item.value">
                  <!-- :class="item.value === params.rate ? 'grid-content active' : 'grid-content'" 表示给图片比例参数选中样式 -->
                  <div class="flex-col items-center"
                       :class="item.value === params.rate ? 'grid-content active' : 'grid-content'"
                       @click="changeRate(item)">
                    <el-image class="icon" :src="item.img" fit="cover"></el-image>
                    <div class="text">{{ item.text }}</div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <!--  图片画质选择 -->
            <div class="param-line" style="padding-top: 10px">
              <el-form-item label="图片画质">
                <template #default>
                  <div class="form-item-inner flex-row items-center">
                    <el-select v-model="params.quality" placeholder="请选择" style="width:150px">
                      <el-option v-for="item in options" :key="item.value" :label="item.label"
                                 :value="item.value"></el-option>
                    </el-select>
                    <el-tooltip content="生成的图片质量，质量越好出图越慢" placement="right">
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </el-form-item>
            </div>
            <!--  模型标题提示 -->
            <div class="param-line pt">
              <span>模型选择：</span>
              <el-tooltip content="MJ: 偏真实通用模型 <br/>NIJI: 偏动漫风格、适用于二次元模型" raw-content
                          placement="right">
                <el-icon>
                  <InfoFilled/>
                </el-icon>
              </el-tooltip>
            </div>
            <!--  模型参数渲染 -->
            <div class="param-line pt">
              <el-row :gutter="10">
                <el-col :span="12" v-for="item in models" :key="item.value">
                  <div :class="item.value === params.model ? 'model active' : 'model'" @click="changeModel(item)">
                    <el-image :src="item.img" fit="cover"></el-image>
                    <div class="text">{{ item.text }}</div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <!--  重复平铺 -->
            <div class="param-line">
              <el-form-item label="重复平铺">
                <template #default>
                  <div class="form-item-inner">
                    <el-switch v-model="params.tile" inactive-color="#464649"/>
                    <el-tooltip content="重复：--tile，参数释义：生成可用作重复平铺的图像，以创建无缝图案。"
                                raw-content placement="right">
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </el-form-item>
            </div>
            <!--  原始模式 -->
            <div class="param-line">
              <el-form-item label="原始模式">
                <template #default>
                  <div class="form-item-inner">
                    <el-switch v-model="params.raw" inactive-color="#464649"/>
                    <el-tooltip content="启用新的RAW模式，呈现的人物写实感更加逼真，人物细节、光源、流畅度也更加接近原始作品。<br/> 同时也意味着您需要添加更长的提示。"
                                raw-content placement="right">
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </el-form-item>
            </div>
            <!--  创意度 -->
            <div class="param-line" style="padding-top: 10px">
              <el-form-item label="创意度">
                <template #default>
                  <div class="form-item-inner">
                    <el-slider v-model.number="params.chaos" :max="100" :step="1" style="width: 180px"/>
                    <el-tooltip content="参数用法：--chaos 或--c，取值范围: 0-100 <br/> 取值越高结果越发散，反之则稳定收敛<br /> 默认值0最为精准稳定"
                                raw-content placement="right">
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </el-form-item>
            </div>
            <!--  风格化 -->
            <div class="param-line">
              <el-form-item label="风格化">
                <template #default>
                  <div class="form-item-inner">
                    <el-slider v-model.number="params.stylize" :min="0" :max="1000" :step="1"
                               style="width: 180px;"/>
                    <el-tooltip content="风格化：--stylize 或 --s，范围 1-1000，默认值100 <br/>高取值会产生非常艺术化但与提示关联性较低的图像"
                                raw-content placement="right">
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </el-form-item>
            </div>
            <!--  随机种子 -->
            <div class="param-line">
              <el-form-item label="随机种子">
                <template #default>
                  <div class="form-item-inner">
                    <el-input v-model.number="params.seed"/>
                    <el-tooltip content="随机种子：--seed，默认值0表示随机产生 <br/>使用相同的种子参数和描述将产生相似的图像"
                                raw-content placement="right">
                      <el-icon>
                        <InfoFilled/>
                      </el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div class="task-list-box  pl-6 pr-6 pb-4 h-dvh">
        <div class="task-list-inner" :style="{height: listBoxHeight + 'px'}">
          <div class="extra-params">
            <el-form>
              <el-tabs v-model="activeName" class="title-tabs" @tabChange="tabChange">
                <el-tab-pane label="文生图" name="txt2img">
                  <div class="prompt-box">
                    <!-- 提示词标题 -->
                    <div class="param-line pt">
                      <div class="flex-row justify-between items-center">
                        <div class="flex-row justify-start items-center">
                          <span>提示词：</span>
                          <el-tooltip content="输入你想要的内容，用逗号分割" placement="right">
                            <el-icon>
                              <InfoFilled/>
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </div>
                    </div>
                    <!-- 提示词输入框 -->
                    <div class="param-line pt" style="position: relative">
                      <el-input v-model="params.prompt" :autosize="{ minRows: 4, maxRows: 6 }" type="textarea"
                                ref="promptRef" v-loading="isGenerating"
                                placeholder="请在此输入绘画提示词，您也可以点击下面的提示词助手生成绘画提示词"/>
                    </div>
                    <!-- 生成专业绘画指令 -->
                    <el-row class="text-info">
                      <el-button class="generate-btn" size="small" @click="generatePrompt" color="#5865f2"
                                 :disabled="isGenerating">
                        <i class="iconfont icon-chuangzuo"></i>
                        <span>生成专业绘画指令</span>
                      </el-button>
                    </el-row>
                    <!-- 反向提示词标题 -->
                    <div class="param-line pt">
                      <div class="flex-row justify-between items-center">
                        <div class="flex-row justify-start items-center">
                          <span>不希望出现的内容：（可选）</span>
                          <el-tooltip content="不想出现在图片上的元素(例如：树，建筑)" placement="right">
                            <el-icon>
                              <InfoFilled/>
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </div>
                    </div>
                    <!-- 反向提示词输入框 -->
                    <div class="param-line pt">
                      <el-input v-model="params.neg_prompt" :autosize="{ minRows: 4, maxRows: 6 }" type="textarea"
                                ref="promptRef"
                                placeholder="请在此输入你不希望出现在图片上的内容，系统会自动翻译中文提示词"/>
                    </div>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="图生图" name="img2img">
                  <div class="text">图生图：以某张图片为底稿参考来创作绘画，生成类似风格或类型图像，支持 PNG 和 JPG
                    格式图片；
                  </div>
                  <!-- 上传图片 -->
                  <div class="param-line">
                    <div class="img-inline">
                      <div class="img-list-box">
                        <!-- 渲染图片列表 -->
                        <div class="img-item" v-for="imgURL in imgList" :key="imgURL">
                          <el-image :src="imgURL" fit="cover"/>
                          <el-button type="danger" :icon="Delete" @click="removeUploadImage(imgURL)" circle/>
                        </div>
                      </div>
                      <!-- 上传图片 -->
                      <el-upload class="img-uploader" :auto-upload="true" :show-file-list="false"
                                 :http-request="uploadImg">
                        <el-icon class="uploader-icon">
                          <Plus/>
                        </el-icon>
                      </el-upload>
                    </div>
                  </div>
                  <!-- 参考权重 -->
                  <div class="param-line" style="padding-top: 10px">
                    <el-form-item label="参考权重：">
                      <template #default>
                        <div class="form-item-inner">
                          <el-slider v-model.number="params.iw" :max="1" :step="0.01"
                                     style="width: 180px;"/>
                          <el-tooltip content="使用图像权重参数--iw来调整图像 URL 与文本的重要性 <br/>权重较高时意味着图像提示将对完成的作业产生更大的影响"
                                      raw-content placement="right">
                            <el-icon>
                              <InfoFilled/>
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </template>
                    </el-form-item>
                  </div>

                  <div class="prompt-box">
                    <!-- 提示词标题 -->
                    <div class="param-line pt">
                      <div class="flex-row justify-between items-center">
                        <div class="flex-row justify-start items-center">
                          <span>提示词：</span>
                          <el-tooltip content="输入你想要的内容，用逗号分割" placement="right">
                            <el-icon>
                              <InfoFilled/>
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </div>
                    </div>
                    <!-- 提示词输入框 -->
                    <div class="param-line pt">
                      <el-input v-model="params.prompt" :autosize="{ minRows: 4, maxRows: 6 }" type="textarea"
                                ref="promptRef" v-loading="isGenerating"
                                placeholder="请在此输入绘画提示词，系统会自动翻译中文提示词，高手请直接输入英文提示词"/>
                    </div>
                    <!-- 生成专业绘画指令 -->
                    <el-row class="text-info">
                      <el-button class="generate-btn" size="small" @click="generatePrompt" color="#5865f2"
                                 :disabled="isGenerating">
                        <i class="iconfont icon-chuangzuo"></i>
                        <span>生成专业绘画指令</span>
                      </el-button>
                    </el-row>
                    <!-- 反向提示词标题 -->
                    <div class="param-line pt">
                      <div class="flex-row justify-between items-center">
                        <div class="flex-row justify-start items-center">
                          <span>不希望出现的内容：（可选）</span>
                          <el-tooltip content="不想出现在图片上的元素(例如：树，建筑)" placement="right">
                            <el-icon>
                              <InfoFilled/>
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </div>
                    </div>
                    <!-- 反向提示词输入框 -->
                    <div class="param-line pt">
                      <el-input v-model="params.neg_prompt" :autosize="{ minRows: 4, maxRows: 6 }" type="textarea"
                                ref="promptRef"
                                placeholder="请在此输入你不希望出现在图片上的内容，系统会自动翻译中文提示词"/>
                    </div>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="融图" name="blend">
                  <div class="text">
                    请上传两张以上的图片，最多不超过五张，超过五张图片请使用图生图功能
                  </div>
                  <!-- 上传图片 -->
                  <div class="img-inline">
                    <div class="img-list-box">
                      <!-- 渲染图片列表 -->
                      <div class="img-item" v-for="imgURL in imgList" :key="imgURL">
                        <el-image :src="imgURL" fit="cover"/>
                        <el-button type="danger" :icon="Delete" @click="removeUploadImage(imgURL)" circle/>
                      </div>
                    </div>
                    <!-- 上传图片 -->
                    <el-upload class="img-uploader" :auto-upload="true" :show-file-list="false"
                               :http-request="uploadImg">
                      <el-icon class="uploader-icon">
                        <Plus/>
                      </el-icon>
                    </el-upload>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="换脸" name="swapFace">
                  <div class="text">
                    请上传两张有脸部的图片，用左边图片的脸替换右边图片的脸
                  </div>
                  <!-- 上传图片 -->
                  <div class="img-inline">
                    <div class="img-list-box">
                      <!-- 渲染图片列表 -->
                      <div class="img-item" v-for="imgURL in imgList" :key="imgURL">
                        <el-image :src="imgURL" fit="cover"/>
                        <el-button type="danger" :icon="Delete" @click="removeUploadImage(imgURL)" circle/>
                      </div>
                    </div>
                    <!-- 上传图片 -->
                    <el-upload class="img-uploader" :auto-upload="true" :show-file-list="false"
                               :http-request="uploadImg">
                      <el-icon class="uploader-icon">
                        <Plus/>
                      </el-icon>
                    </el-upload>
                  </div>
                </el-tab-pane>

                <el-tab-pane name="cref">
                  <template #label>
                    <el-badge value="New"><span>一致性</span></el-badge>
                  </template>
                  <div class="text">注意：只有于 niji6 和 v6 模型支持一致性功能，如果选择其他模型此功能将会生成失败。</div>
                  <!-- 角色一致性 上传图片 -->
                  <div class="param-line">
                    <el-form-item label="角色一致性：" prop="cref">
                      <el-input v-model="params.cref" placeholder="请输入图片URL或者上传图片"
                                style="--el-input-focus-border-color: #b0a0f8; max-width: 500px; width: 100%"
                                size="small">
                        <template #append>
                          <el-upload :auto-upload="true" :show-file-list="false"
                                     @click="beforeUpload('cref')"
                                     :http-request="uploadImg">
                            <el-icon class="uploader-icon">
                              <UploadFilled/>
                            </el-icon>
                          </el-upload>
                        </template>
                      </el-input>
                    </el-form-item>
                  </div>
                  <!-- 风格一致性 上传图片 -->
                  <div class="param-line">
                    <el-form-item label="风格一致性：" prop="sref">
                      <el-input v-model="params.sref" placeholder="请输入图片URL或者上传图片"
                                style="--el-input-focus-border-color: #b0a0f8; max-width: 500px; width: 100%"
                                size="small">
                        <template #append>
                          <el-upload :auto-upload="true" :show-file-list="false"
                                     @click="beforeUpload('sref')"
                                     :http-request="uploadImg">
                            <el-icon class="uploader-icon">
                              <UploadFilled/>
                            </el-icon>
                          </el-upload>
                        </template>
                      </el-input>
                    </el-form-item>
                  </div>

                  <!-- 参考权重 -->
                  <div class="param-line" style="padding-top: 10px">
                    <el-form-item label="参考权重：">
                      <template #default>
                        <div class="form-item-inner">
                          <el-slider v-model.number="params.cw" :max="100" :step="1"
                                     style="width: 180px;"/>
                          <el-tooltip content="取值范围 0-100 <br/>默认值100参考原图的脸部、头发和衣服<br/>0则表示只换脸"
                                      raw-content placement="right">
                            <el-icon>
                              <InfoFilled/>
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </template>
                    </el-form-item>
                  </div>

                  <div class="prompt-box">
                    <!-- 提示词标题 -->
                    <div class="param-line pt">
                      <div class="flex-row justify-between items-center">
                        <div class="flex-row justify-start items-center">
                          <span>提示词：</span>
                          <el-tooltip content="输入你想要的内容，用逗号分割" placement="right">
                            <el-icon>
                              <InfoFilled/>
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </div>
                    </div>
                    <!-- 提示词输入框 -->
                    <div class="param-line pt">
                      <el-input v-model="params.prompt" :autosize="{ minRows: 4, maxRows: 6 }" type="textarea"
                                ref="promptRef" v-loading="isGenerating"
                                placeholder="请在此输入绘画提示词，系统会自动翻译中文提示词，高手请直接输入英文提示词"/>
                    </div>
                    <!-- 反向提示词标题 -->
                    <div class="param-line pt">
                      <div class="flex-row justify-between items-center">
                        <div class="flex-row justify-start items-center">
                          <span>不希望出现的内容：（可选）</span>
                          <el-tooltip content="不想出现在图片上的元素(例如：树，建筑)" placement="right">
                            <el-icon>
                              <InfoFilled/>
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </div>
                    </div>
                    <!-- 反向提示词输入框 -->
                    <div class="param-line pt">
                      <el-input v-model="params.neg_prompt" :autosize="{ minRows: 4, maxRows: 6 }" type="textarea"
                                ref="promptRef"
                                placeholder="请在此输入你不希望出现在图片上的内容，系统会自动翻译中文提示词"/>
                    </div>
                  </div>
                </el-tab-pane>

              </el-tabs>
              <el-row class="text-info">
                <el-text type="primary">
                  每次绘图消耗<el-text type="warning">{{ mjPower }}算力;</el-text>
                  &nbsp;&nbsp; U/V 操作消耗<el-text type="warning">{{ mjActionPower }}算力;</el-text>
                  &nbsp;&nbsp;<el-text type="primary">当前可用算力：<el-text type="warning">{{ power }}</el-text></el-text>
                </el-text>
              </el-row>
              <div class="submit-btn">
                <el-button type="primary" :dark="false" @click="generate" round>立即生成</el-button>
              </div>
            </el-form>
          </div>
          <div class="job-list-box">
            <h2 class="text-xl">任务列表</h2>
            <task-list :list="runningJobs"/>

            <template v-if="finishedJobs.length > 0">
              <h2 class="text-xl">创作记录</h2>
              <div class="finish-job-list">
                <div v-if="finishedJobs.length > 0">
                  <!-- v3-waterfall：vue 3 的自适应瀑布流组件
                       list：瀑布流列表数据
                       srcKey：指定数据项中图片URL的字段名。组件会从每个数据项的thumb_url属性中获取图片地址。
                       gap：两列间的间距，单位：px
                       bottomGap：上下卡片的间距，单位：px
                       colWidth：瀑布流卡片宽度，现在不同屏宽使用不同宽度需要自己写函数返回对应宽度
                       distanceToScroll：底部触发加载的距离，单位：px
                       isLoading：控制请求数据时显示加载状态提示
                       isOver：控制数据是否已经全部加载完成(即不需要再滚动加载)
                       @srcollReachBottom：：当滚动到底部（或距离底部指定距离）时，触发fetchFinishJobs方法（加载更多数据）。
                   -->
                  <v3-waterfall id="waterfall"
                                :list="finishedJobs"
                                srcKey="thumb_url"
                                :gap="20"
                                :bottomGap="-8"
                                :colWidth="colWidth"
                                :distanceToScroll="100"
                                :isLoading="loading"
                                :isOver="isOver"
                                @scrollReachBottom="fetchFinishJobs()">
                    <template #default="slotProp">
                      <div class="job-item">
                        <!-- 显示图片 -->
                        <el-image v-if="slotProp.item.img_url !== ''" :src="slotProp.item['thumb_url']"
                                  :class="slotProp.item['can_opt'] ? '' : 'upscale'" @click="previewImg(slotProp.item)"
                                  fit="cover" :initial-index="slotProp.index" loading="lazy">
                          <template #placeholder>
                            <div class="image-slot">正在加载图片</div>
                          </template>
                          <template #error>
                            <div class="image-slot">
                              <el-icon>
                                <Picture/>
                              </el-icon>
                            </div>
                          </template>
                        </el-image>
                        <!-- 错误任务默认显示 -->
                        <el-image v-else-if="slotProp.item.progress === 101">
                          <template #error>
                            <div class="image-slot">
                              <div class="err-msg-container">
                                <div class="title">任务失败</div>
                                <div class="opt">
                                  <el-popover title="错误详情" trigger="click" :width="250"
                                              :content="slotProp.item['err_msg']" placement="top">
                                    <template #reference>
                                      <el-button type="info">详情</el-button>
                                    </template>
                                  </el-popover>
                                  <el-button type="danger" @click="removeImage(slotProp.item)">删除</el-button>
                                </div>
                              </div>
                            </div>
                          </template>
                        </el-image>
                        <!-- 正在下载图片显示，img_url 为空表示正在下载图片 -->
                        <el-image v-else>
                          <template #error>
                            <div class="image-slot">
                              <i class="iconfont icon-loading"></i>
                              <span>正在下载图片</span>
                            </div>
                          </template>
                        </el-image>
                        <div class="opt" v-if="slotProp.item['can_opt']">
                          <div class="opt-line">
                            <ul>
                              <li><a @click="upscale(1,slotProp.item)">U1</a></li>
                              <li><a @click="upscale(2,slotProp.item)">U2</a></li>
                              <li><a @click="upscale(3,slotProp.item)">U3</a></li>
                              <li><a @click="upscale(4,slotProp.item)">U4</a></li>
                              <!-- 显示提示词 -->
                              <li class="show-prompt">
                                <el-popover placement="left" title="提示词" :width="240" trigger="hover">
                                  <template #reference>
                                    <el-icon>
                                      <ChromeFilled/>
                                    </el-icon>
                                  </template>
                                  <template #default>
                                    <div class="mj-list-item-prompt">
                                      <span>{{ slotProp.item.prompt }}</span>
                                      <el-icon class="copy-prompt-mj" :data-clipboard-text="slotProp.item.prompt">
                                        <DocumentCopy/>
                                      </el-icon>
                                    </div>
                                  </template>
                                </el-popover>
                              </li>
                            </ul>
                          </div>
                          <div class="opt-line">
                            <ul>
                              <li><a @click="variation(1,slotProp.item)">V1</a></li>
                              <li><a @click="variation(2,slotProp.item)">V2</a></li>
                              <li><a @click="variation(3,slotProp.item)">V3</a></li>
                              <li><a @click="variation(4,slotProp.item)">V4</a></li>
                            </ul>
                          </div>
                        </div>
                        <!-- 显示图片操作按钮 -->
                        <div class="remove" v-if="slotProp.item.progress === 100">
                          <el-tooltip effect="light" content="删除任务" placement="top">
                            <el-button type="danger" :icon="Delete" @click="removeImage(slotProp.item)" circle />
                          </el-tooltip>
                          <el-tooltip effect="light" content="取消发布" placement="top" v-if="slotProp.item.publish">
                            <el-button type="warning"  @click="publishImage(slotProp.item,false)" circle><i class="iconfont icon-cancel-share"></i></el-button>
                          </el-tooltip>
                          <el-tooltip effect="light" content="发布图片" placement="top" v-else>
                            <el-button type="success"  @click="publishImage(slotProp.item,true)" circle><i class="iconfont icon-share-bold"></i></el-button>
                          </el-tooltip>
                          <el-tooltip effect="light" content="复制提示词" placement="top">
                            <el-button type="success" class="copy-prompt-mj"  :data-clipboard-text="slotProp.item.prompt" circle><el-icon><DocumentCopy/></el-icon></el-button>
                          </el-tooltip>
                        </div>
                      </div>
                    </template>
                    <template #footer>
                      <div class="no-more-data">
                        <span>没有更多数据了</span>
                        <i class="iconfont icon-face"></i>
                      </div>
                    </template>
                  </v3-waterfall>
                </div>
                <el-empty :image-size="100" :image="nodata" description="暂无记录" v-else/>
              </div>
            </template>
          </div>
        </div>
        <back-top :right="30" :bottom="30"/>
      </div>
    </div>
    <!-- 图片预览 -->
    <el-image-viewer @close="() => {previewURL = ''}" v-if="previewURL !== ''" :url-list="[previewURL]"/>
  </div>
</template>

<style lang="stylus">
@import "../assets/css/image-mj.styl"
@import "../assets/css/custom-scroll.styl"
</style>